<template>
  <div>
    <v-alert transition="scale-transition" :value="pageUrl" type="success">
      <a :href="pageUrl">{{pageUrl}}</a>
    </v-alert>
    <template v-for="(block, index) in blocks">
      <!-- <v-checkbox :key="index" v-model="block.checked" :label="block.name"></v-checkbox> -->
      <v-btn
        :key="`btn-${index}`"
        color="primary"
        depressed
        @click="activeSetter(index)"
      >{{block.name}}</v-btn>
    </template>
    <v-navigation-drawer v-model="currentSetter" right fixed clipped app>
      <v-container>
        <component v-if="currentSetter" v-bind:is="currentSetter" v-on:setting="setting"></component>
      </v-container>
    </v-navigation-drawer>
    <v-textarea readonly v-model="vString" outline rows="5"/>
    <v-btn :loading="loading" color="primary" @click="submit">生成页面</v-btn>
  </div>
</template>

<script>
import { addCollection } from '../services/collection'
import blocks from '../blocks'

const blockKeys = Object.keys(blocks)

const blockComponents = {}
const setterComponents = {}

blockKeys.forEach(keys => {
  blockComponents[keys] = blocks[keys].block
  setterComponents[`${keys}-Setter`] = blocks[keys].setter
})

const blocksArray = blockKeys.map(key => ({
  checked: false,
  name: key
}))

export default {
  components: {
    ...blockComponents,
    ...setterComponents
  },
  data() {
    return {
      currentSetter: '',
      loading: false,
      vString: '[]',
      pageUrl: '',
      blocks: blocksArray
    }
  },
  methods: {
    activeSetter(index) {
      this.currentSetter = `${this.blocks[index].name}-Setter`
    },
    setting({ name, config, data }) {
      const vjson = JSON.parse(this.vString)
      if (Array.isArray(vjson)) {
        vjson.push({
          name,
          config,
          data
        })
        this.vString = JSON.stringify(vjson)
      }
      console.log(name, config, data)
    },
    async submit() {
      this.loading = true

      try {
        const res = await addCollection({
          type: 'page',
          content: this.vString
        })

        this.loading = false
        this.pageUrl = `/${res.data._id}`
      } catch (error) {
        this.loading = false
      }
    }
  }
}
</script>

